package com.grape.demo20220803.service.impl;

import com.grape.demo20220803.service.StorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.UUID;

/**
 * @Author pan_jin
 * @Description: $
 * @Date: 2022/8/8 10:08
 * @Version: 1.0.0
 * @Slogan: 梦想还是要有的万一实现了呢
 */
@Component
//@Profile("default")
@ConditionalOnProperty(value = "storage.type", havingValue = "local", matchIfMissing = true)
public class LocalStorageService implements StorageService {

    @Value("${storage.local:D:\\storage")
    private String localStorageRootDir;

    private File localStorageRoot;

    @PostConstruct
    void init() {
        this.localStorageRoot = new File(localStorageRootDir);
    }

    @Override
    public InputStream openInputStream(String url) throws IOException {
        File file = new File(this.localStorageRoot, url);
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        return inputStream;
    }

    @Override
    public String store(String extName, InputStream input) throws IOException {
        String fileName = UUID.randomUUID().toString() + "." + extName;
        File file = new File(this.localStorageRoot, fileName);
        try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));) {
            input.transferTo(outputStream);
        }

        return fileName;
    }
}
